<?php

namespace App\Http\Controllers;

use App\Models\DecSubject;
use App\Models\DictionaryItem;
use App\Models\Faculty\PlatformCredit;
use App\Models\System\User;
use App\Models\Teachers;
use App\Models\YxhdInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

/**
 * 提供 dec 服务的控制器。
 */
class DecController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->middleware('request.logger');
        // 关闭调试栏输出
        if (class_exists('\Debugbar')) {
            \Debugbar::disable();
        }
    }

    /**
     * 提供给DEC访问的 接口服务。
     */
    public function index(Request $request){
        try
        {
            $action = $request->action;
            $data = $request->data;
            $data = json_decode($data, TRUE );
            switch ($action)
            {
                case "data_change":
                    $this->saveDecData($data);
                    break;
                case "data_delete":
                    $this->deleteDecData($data);
                    break;
            }

            return [
                "error_code" => 0
            ];
        }
        catch(\Exception $e)
        {
            return [
                'error_code' => 1,
                'error_message'  => $e->getMessage(),
            ];
        }
    }

    public function saveDecData($data)
    {
        try
        {
            $dataArray = $data['data_array'];
            foreach ($dataArray as $d){
                $category = $d['category'];
                switch ($category)
                {
                    case "sx_teacher":
                        $teacherData = [
                            'id_no' => $d['id'],
                            'name' => $d['name'] ?? '',
                            'teacher_no' => $d['sx_number'],
                                // 'user_name' => $d['sx_username'],
                             'gender' => $d['sex'] ?? '',
                            'birthday' => $d['birthday'] ?? '',
                            'mobile' => $d['tel_num'] ?? '',
//                            'phone_num' => $d['phone'],
//                            'email' => $d['email'],
                                // 'school' => $d['school'],
                                // 'school_org_code' => $d['school_org_code'],
                             'nation' => $d['nation'] ?? '',
                            // 'political' => $d['zzmm'],
                            'zzmm' => $d['zzmm'] ?? '',
                            'sx_id' => $d['sx_id'] ?? '',
                            'eduid' => $d['eduid'] ?? '',
                                // 'zc' => $d['zc'],
                                // 'zw' => $d['zw'],
                                // 'employee_date' => $d['employee_date'],
                            // 'work_date' => $d['off_start'],
                                // 'app_starttime' => $d['app_starttime'],
                            'teacher_certificate_no' => $d['jszgz_no'] ?? '',
                            // 'deleted' => $d['is_del']//0-正常，1-已删院
                        ];

                        $dics = DictionaryItem::select('item_order as order','id as optionId','parent_id as parentId','item_value as selectKey','item_name as selectValue', 'code')->where('deleted', 0)->get();

                        if(isset($d['sex']) && $d['sex']) {
                            $gender = $dics->where('code', 'gender')->where('selectValue', $d['sex'])->first();
                            $teacherData['gender'] = $gender ? json_encode([$gender->toArray()]) : '';
                        }

                        if(isset($d['nation']) && $d['nation']) {
                            $nation = $dics->where('code', 'nation')->where('selectValue', $d['nation'])->first();
                            $teacherData['nation'] = $nation ? json_encode([$nation->toArray()]) : '';
                        }

                        // 部分数据不能和字典进行匹配导致空值，暂停止同步更新
                        // if(isset($d['zzmm']) && $d['zzmm']) {
                        //     $political = $dics->where('code', 'political')->where('selectValue', $d['zzmm'])->first();
                        //     $teacherData['political'] = $political ? json_encode([$political->toArray()]) : '';
                        // }

                        if(isset($d['master_subject']) && $d['master_subject']) {
                            $subject = $dics->where('code', 'TEACHER_SUBJECT')->where('selectValue', $d['master_subject'])->first();
                            $teacherData['major_subject'] = $subject ? json_encode([$subject->toArray()]) : '';
                        }

                        // if($d['birthday']) {
                        //     $age = Carbon::parse($d['birthday'])->diffInYears();
                        //     $teacherData['age'] = $age;
                        // }

                        $user = User::where('eduid', $d['eduid'])->first();
                        if($user && $d['eduid']) {
                            $teacherData['user_id'] = $user->id;

                            $lastGroup = User::lastgroup($user->group_id);
                            if($lastGroup) {
                                // 非在编在岗人员、区内轮岗教师、临时账号、已退休离职人员
                                // 12405	非在编在岗人员
                                // 11801	临时账号
                                // 12868	区内轮岗教师
                                // 17564	已退休离职人员
                                $teacherData['last_group_id'] = $lastGroup->group_id;
                            }
                        }

                        /** @var \App\Services\System\TeacherService $teacherService */
                        $teacherService = app('teacherService');
                        $teacherService->updateOrCreateCore(
                            ['eduid' => $d['eduid']],
                            $teacherData
                        );
                        break;
                    case "xhjw_classroom":
                        $grade = isset($d['grade']) ? trim($d['grade']) : '';
                        if ($grade){
                            $classModel = DictionaryItem::query()->where(['item_order' => $d['id']])->first();
                            $gradeModel = $classModel?
                                DictionaryItem::query()
                                    ->updateOrCreate(['id' =>$classModel->parent_id], ['item_name' => $grade])
                                :DictionaryItem::query()
                                ->updateOrCreate(['code' => 'GRADE', 'item_name'=>$grade]);
                            $classroomData = [
                                'parent_id' => $gradeModel->id,
                                'code' => 'CLASS',
                                'item_name' => $d['class_title'] ?? '',
                                'item_order' => $d['id'],
                            ];
                            DictionaryItem::query()->updateOrCreate(
                                ['item_order' => $d['id']],
                                $classroomData
                            );
                        }
                        break;
                    case "xhjw_term_cycle":
                        $schoolYear = $d['school_year'] ?? '';
                        $term = $d['term'] ?? '';

                        $title = $schoolYear.$term;
                        $termData = [
                            // 'id' => $d['id'],
                            'title' => $title,
                            'start_date' => $d['start_time'] ?? '',
                            'end_date' => $d['end_time'] ?? '',
                            'activity_end_date' => $d['end_time'] ?? '',
                            'description' => $title.$d['id'],
                            'created_at' => date("Y-m-d H:i:s"),
                            'updated_at' => date("Y-m-d H:i:s"),
                        ];
                        foreach ($termData as $key=>$value){
                            if(empty($value)){
                                unset($termData[$key]);
                            }
                        }
                        /** @var \App\Services\System\TermService $termService */
                        $termService = app('termService');
                        $termService->updateOrCreateCore(
                            ['title' => $title],
                            $termData
                        );
                        break;
                    case "sx_score":
                        $scoreData = [
                            'record_id' => $d['id'],
//                            'id_card' => $d['sfzjh'],
                            'course_name' => $d['course_name'] ?? '',
                            'sx_id' => $d['sx_id'],
                            'course_level' => $d['course_level'] ?? '',
                            // 'course_cap' => $d['course_cap'] ? $d['course_cap'] : '',
                            'score' => $d['score'] ?? '',
                            'get_time' => $d['gettimes'] ?: date("Y-m-d H:i:s")
                        ];

                        $user = Teachers::query()->where('sx_id', $d['sx_id'])->first();
                        if($user) {
                            $scoreData['user_id'] = $user->id;
                            $scoreData['user_name'] = $user->nickname;
                        }

                        // 时期处理
//                        $getYear = date('Y', strtotime($scoreData['get_time']));

//                        $dicItem = Dicitem::where('diccode', 'PXSQ')
//                            ->where('itemcode', '>', $getYear)
//                            ->orderBy('itemcode', 'asc')
//                            ->first();
//                        $scoreData['term'] = $dicItem->itemname;
//                        $scoreData['term_dic'] = $dicItem->id;

                        foreach ($scoreData as $key=>$value){
                            if(empty($value)){
                                unset($scoreData[$key]);
                            }
                        }

                        PlatformCredit::updateOrCreate(['record_id' => $d['id']], $scoreData);
                        break;
                    case "jy_yxhd_info":
                        $yxhdInfo = Arr::only($d, [
                            'id', 'sx_class_id', 'yxzt', 'start_time', 'end_time', 'yxxs', 'yx_type', 'address',
                            'yx_target', 'yx_content', 'msg_content', 'hd_creator', 'admin2', 'is_open',
                            'open_certificate', 'hs_status', 'xd', 'subject', 'verify_status', 'creator']);
                        YxhdInfo::query()->updateOrCreate(
                            ['id' => $d['id']],
                            $yxhdInfo
                        );
                        break;
                    case "xhjw_subject":
                        $decSubject = Arr::only($d, [
                            'id', 'name']);
                        DecSubject::query()->updateOrCreate(
                            ['id' => $d['id']],
                            $decSubject
                        );
                        break;
                }
            }
        }
        catch(\Exception $e)
        {
            Log::error($e);
            throw $e;
        }
    }

    public function deleteDecData($data)
    {
        try
        {
            $dataArray = $data['data_array'];
            foreach ($dataArray as $d){
                $category = $d['category'];
                switch ($category)
                {
                    case "sx_teacher":
                        /** @var \App\Services\System\TeacherService $teacherService */
                        $teacherService = app('teacherService');
                        $teacherService->deleteCore(
                            ['id_card' => $d['id']],
                            false
                        );
                        break;
                    case "xhjw_classroom":
                        DictionaryItem::query()->where('code', 'CLASS')
                            ->where('item_order', $d['id'])
                            ->delete();
                        break;
                    case "xhjw_term_cycle":
                        /** @var \App\Services\System\TermService $termService */
                        $termService = app('termService');
                        $termService->deleteCore($d['id']);
                        break;
                }
            }
        }
        catch(\Exception $e)
        {
            Log::error($e);
            throw $e;
        }
    }
}
